package core

import (
	"net"
	"share/app"
	"share/msg"
	"util/log"
	"world/config"
)

var (
	world = &World{}
)

type World struct {
	appClient *app.AppClient
	servSock  *ServSock
	mquit     chan bool
	cfg       *config.Config
	runchan   chan bool
}

func (w *World) Start(c *config.Config, ch chan bool) {
	w.cfg = c
	w.mquit = ch
	w.runchan = make(chan bool)
	w.initAll()
	w.run()
}

func (w *World) initAll() {
	w.appClient = app.CreateAppClient()
	w.servSock = CreateServSock(w.cfg.ServIp, w.cfg.ServPort)
}

func (w *World) run() {

	if err := w.servSock.Start(1); err != nil {
		panic("serv sock failed")
	}

	addr, _ := w.servSock.Addr().(*net.TCPAddr)

	w.appClient.Run(w.cfg.CenterIp, w.cfg.CenterPort, msg.AT_WORLD, addr.IP.String(), addr.Port)

	log.TraceInfo("world", "service start")

loop:
	for {
		select {
		case <-w.runchan:
			break loop
		}
	}

	w.appClient.Shutdown()

	w.mquit <- true
}

func (w *World) shutdown() {
	w.runchan <- true
}

func GetWorld() *World {
	return world
}

func ServiceQuit() {
	world.shutdown()
}
